﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using A2DFramework.ServiceLocatorService;
using System.ServiceModel;

namespace A2DFramework.InternalCommunicationService
{
    public class ICSFactory
    {
        /// <summary>
        /// 创建WCF服务代理对象
        /// </summary>
        /// <typeparam name="T">WCF的Contract类型</typeparam>
        /// <returns></returns>
        public static T Create<T>()
        {
            return Create<T>(string.Empty);
        }

        /// <summary>
        /// 创建WCF服务代理对象
        /// </summary>
        /// <typeparam name="T">WCF的Contract类型</typeparam>
        /// <returns></returns>
        public static T Create<T>(string version)
        {
            string contractNamespace = typeof(T).Namespace;
            string contract = typeof(T).Name;

            //根据WCF Contract信息找到相应的位置信息
            Location location = ServiceLocator.Locate(contractNamespace, contract, version);

            //生成绑定信息
            NetTcpBinding binding = new NetTcpBinding();
            binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
            binding.Security.Mode = SecurityMode.None;
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;

            //事务设置
            binding.TransactionFlow = true;
            binding.TransactionProtocol = TransactionProtocol.OleTransactions;

            //地址信息
            EndpointAddress address = new EndpointAddress(location.Url);

            //建立信道
            T broker=ChannelFactory<T>.CreateChannel(binding, address);

            //返回代理对象
            return broker;
        }

        /// <summary>
        /// Dispose代理对象
        /// </summary>
        /// <param name="broker"></param>
        public static void Close(object broker)
        {
            if (broker == null)
                return;

            IDisposable disposable = broker as IDisposable;
            if (disposable == null)
                return;

            disposable.Dispose();
        }
    }
}
